package com.zeny.edu.oss.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.zeny.edu.common.ResponseResult;
import com.zeny.edu.oss.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName FileUploadController
 * @Description oss服务
 * @Author zeny
 * @Date 2020/2/27 22:21
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class FileUploadController {

    /**
     * 图片上传
     *
     * @param file       文件
     * @param folderName 文件夹名字
     * @return
     */
    @PostMapping("/oss/upload")
    public ResponseResult upload(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "teacher/img/",required = false) String folderName) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String yourBucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;
        try {
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            String filePath = new DateTime().toString("yyyy/MM/dd");
            filename = folderName + filePath + "/" + uuid + filename;
            InputStream in = file.getInputStream();
            OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            //第一个参数BucketName，第二个参数文件名称，第三个参数文件输入流
            ossClient.putObject(yourBucketName, filename, in);

            ossClient.shutdown();
            //返回oss存储路径
            String path = fileHost + filename;
            //保存路径到数据库
            return ResponseResult.ok().data("imgUrl", path);
        } catch (Exception e) {
            return ResponseResult.fail();
        }
    }

}
